package JUC.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author mubei
 * @date 2021/11/21
 * @description
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();


        for (int i = 0; i < 5; i++) {
            int temp = i;
            new Thread(()->{
                myCache.put(temp+"",temp+"值");
            }).start();
        }

        for (int i = 0; i < 5; i++) {
            int temp = i;
            new Thread(()->{
                myCache.get(temp+"");
            }).start();
        }
    }

}


class MyCacheLock{

    private ReadWriteLock lock = new ReentrantReadWriteLock();
    private volatile Map<String,Object> map = new HashMap<>();

    public void put(String key,Object value){
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"写入");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入ok");
        }finally {
            lock.writeLock().unlock();
        }

    }

    public Object get(String key){
        lock.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"读取");

        }finally {
            lock.readLock().unlock();
        }
        return map.get(key);
    }

}


class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();

    public void put(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"写入");
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入ok");
    }

    public Object get(String key){
        System.out.println(Thread.currentThread().getName()+"读取");
        return map.get(key);
    }

}
